<!-- src/view/employee.vue -->
<template>
  <div class="employee-container">
    <h1>员工管理</h1>

    <!-- 查询员工 -->
    <el-card class="search-card">
      <el-form :model="query" label-width="80px" inline>
        <el-form-item label="姓名">
          <el-input v-model="query.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="query.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchEmployees">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增员工 -->
    <div class="toolbar">
      <el-button type="primary" @click="openAddDialog">新增员工</el-button>
    </div>

    <!-- 员工表格 -->
    <el-table
        :data="pagedData"
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
        :height="tableHeight"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="头像" width="100">
        <template #default="scope">
          <img v-if="scope.row.photo" :src="scope.row.photo" class="table-avatar" />
          <span v-else>无头像</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80" />
      <el-table-column prop="birthday" label="生日" width="120">
        <template #default="scope">{{ formatDate(scope.row.birthday) }}</template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-if="total > 0"
        background
        layout="prev, pager, next, sizes, total"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; justify-content: center;"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="editForm.id ? '编辑员工' : '新增员工'"
        width="500px"
    >
      <el-form :model="editForm" label-width="100px" ref="empForm">
        <el-form-item label="姓名" :rules="[{ required: true, message: '请输入姓名', trigger: 'blur' }]">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="editForm.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker v-model="editForm.birthday" type="date" placeholder="选择生日" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              :http-request="customEditAvatarUpload"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="editAvatarUrl" :src="editAvatarUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon">上传头像</i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import employeeApi from '../api/employeeapi.js';
import uploadHttp from '../util/uploadRequest.js';

// 数据和分页
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableHeight = ref(500);

// 计算分页数据
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 查询条件
const query = reactive({ name: '', phone: '' });

// 表单
const dialogVisible = ref(false);
const editForm = reactive({ id: null, name: '', gender: '', birthday: '', phone: '', photo: '' });
const avatarUrl = ref('');
const editAvatarUrl = ref('');

// 加载员工
const loadEmployees = async () => {
  loading.value = true;
  try {
    const res = await employeeApi.list(query);
    if (res && res.code === 200) {
      // 根据后端实际返回的数据结构进行处理
      if (Array.isArray(res.data)) {
        // 如果后端直接返回数组
        tableData.value = res.data;
        total.value = res.data.length;
      } else if (res.data.items) {
        // 如果后端返回包含items和total的对象
        tableData.value = Array.isArray(res.data.items) ? res.data.items : [];
        total.value = res.data.total || res.data.items.length;
      } else {
        // 其他情况，默认为空数组
        tableData.value = [];
        total.value = 0;
      }
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (err) {
    console.error(err);
    tableData.value = [];
    total.value = 0;
    ElMessage.error('获取员工列表失败');
  } finally {
    loading.value = false;
  }
};

// 查询
const searchEmployees = () => {
  currentPage.value = 1;
  loadEmployees();
};

const resetSearch = () => {
  query.name = '';
  query.phone = '';
  currentPage.value = 1;
  loadEmployees();
};

// 分页
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  loadEmployees();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  loadEmployees();
};

// 打开新增/编辑对话框
const openAddDialog = () => {
  Object.assign(editForm, { 
    id: null, 
    name: '', 
    gender: '', 
    birthday: '', 
    phone: '', 
    photo: '',
    departmentId: null,
    position: '',
    hireDate: '',
    status: 1,
    isDeleted: 0
  });
  avatarUrl.value = '';
  dialogVisible.value = true;
};

const openEditDialog = (emp) => {
  // 创建一个包含所有字段的副本
  const empCopy = { 
    id: emp.id, 
    name: emp.name || '', 
    gender: emp.gender || '', 
    birthday: emp.birthday || '', 
    phone: emp.phone || '', 
    photo: emp.photo || '',
    departmentId: emp.departmentId !== undefined ? emp.departmentId : null,
    position: emp.position || '',
    hireDate: emp.hireDate || '',
    status: emp.status !== undefined ? emp.status : 1,
    isDeleted: emp.isDeleted !== undefined ? emp.isDeleted : 0
  };
  
  // 处理日期格式
  if (empCopy.birthday && !(empCopy.birthday instanceof Date)) {
    // 如果是字符串日期，转换为Date对象用于表单显示
    // 兼容不同日期格式
    let birthdayDate;
    if (typeof empCopy.birthday === 'string' && empCopy.birthday.includes('T')) {
      // ISO格式日期
      birthdayDate = new Date(empCopy.birthday);
    } else if (typeof empCopy.birthday === 'string') {
      // YYYY-MM-DD格式或完整日期格式日期
      if (empCopy.birthday.includes(' ')) {
        // 完整日期格式 "yyyy-MM-dd HH:mm:ss"
        birthdayDate = new Date(empCopy.birthday.replace(' ', 'T'));
      } else {
        // YYYY-MM-DD格式日期
        birthdayDate = new Date(empCopy.birthday + 'T00:00:00');
      }
    } else {
      // 其他情况
      birthdayDate = new Date(empCopy.birthday);
    }
    
    if (!isNaN(birthdayDate.getTime())) {
      empCopy.birthday = birthdayDate;
    }
  }
  
  if (empCopy.hireDate && !(empCopy.hireDate instanceof Date)) {
    // 如果是字符串日期，转换为Date对象用于表单显示
    let hireDate;
    if (typeof empCopy.hireDate === 'string' && empCopy.hireDate.includes('T')) {
      // ISO格式日期
      hireDate = new Date(empCopy.hireDate);
    } else if (typeof empCopy.hireDate === 'string') {
      // YYYY-MM-DD格式或完整日期格式日期
      if (empCopy.hireDate.includes(' ')) {
        // 完整日期格式 "yyyy-MM-dd HH:mm:ss"
        hireDate = new Date(empCopy.hireDate.replace(' ', 'T'));
      } else {
        // YYYY-MM-DD格式日期
        hireDate = new Date(empCopy.hireDate + 'T00:00:00');
      }
    } else {
      // 其他情况
      hireDate = new Date(empCopy.hireDate);
    }
    
    if (!isNaN(hireDate.getTime())) {
      empCopy.hireDate = hireDate;
    }
  }
  
  Object.assign(editForm, empCopy);
  editAvatarUrl.value = emp.photo || '';
  dialogVisible.value = true;
};

// 提交
const submitEdit = async () => {
  if (!editForm.name) return ElMessage.warning('姓名不能为空');
  try {
    // 创建一个用于提交的表单副本
    const submitForm = { ...editForm };
    
    // 格式化生日日期
    if (submitForm.birthday instanceof Date) {
      // 格式化为后端期望的完整日期格式
      const date = submitForm.birthday;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      submitForm.birthday = `${year}-${month}-${day} 00:00:00`;
    } else if (typeof submitForm.birthday === 'string' && submitForm.birthday) {
      // 如果是字符串，检查是否需要转换格式
      if (!submitForm.birthday.includes(' ')) {
        // 只有日期部分，补充时间部分
        const date = new Date(submitForm.birthday + 'T00:00:00');
        if (!isNaN(date.getTime())) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          submitForm.birthday = `${year}-${month}-${day} 00:00:00`;
        }
      }
    } else {
      // 如果生日为空或无效值，设置为null
      submitForm.birthday = null;
    }
    
    // 格式化入职日期
    if (submitForm.hireDate instanceof Date) {
      // 格式化为后端期望的完整日期格式
      const date = submitForm.hireDate;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      submitForm.hireDate = `${year}-${month}-${day} 00:00:00`;
    } else if (typeof submitForm.hireDate === 'string' && submitForm.hireDate) {
      // 如果是字符串，检查是否需要转换格式
      if (!submitForm.hireDate.includes(' ')) {
        // 只有日期部分，补充时间部分
        const date = new Date(submitForm.hireDate + 'T00:00:00');
        if (!isNaN(date.getTime())) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          submitForm.hireDate = `${year}-${month}-${day} 00:00:00`;
        }
      }
    } else {
      // 如果入职日期为空或无效值，设置为null
      submitForm.hireDate = null;
    }
    
    // 确保数值类型字段正确
    if (submitForm.departmentId !== null && submitForm.departmentId !== undefined) {
      submitForm.departmentId = Number(submitForm.departmentId);
    }
    
    if (submitForm.status !== null && submitForm.status !== undefined) {
      submitForm.status = Number(submitForm.status);
    }
    
    if (submitForm.isDeleted !== null && submitForm.isDeleted !== undefined) {
      submitForm.isDeleted = Number(submitForm.isDeleted);
    }
    
    console.log('提交的员工数据:', submitForm);
    
    if (editForm.id) await employeeApi.edit(submitForm);
    else await employeeApi.add(submitForm);
    dialogVisible.value = false;
    loadEmployees();
    ElMessage.success('操作成功');
  } catch (err) {
    console.error('操作失败:', err);
    ElMessage.error('操作失败: ' + (err.response?.data?.msg || err.message || '未知错误'));
  }
};

// 删除
const confirmDelete = async (id) => {
  ElMessageBox.confirm('确定要删除该员工吗？', '删除确认', { type: 'warning' })
      .then(async () => {
        try {
          await employeeApi.del(id);
          ElMessage.success('删除成功');
          // 如果当前页只剩一项数据，删除后返回上一页
          if (pagedData.value.length === 1 && currentPage.value > 1) {
            currentPage.value--;
          }
          loadEmployees();
        }
        catch (err) {
          console.error(err);
          ElMessage.error('删除失败');
        }
      }).catch(() => ElMessage.info('已取消删除'));
};

// 格式化日期
const formatDate = (dateString) => dateString ? new Date(dateString).toISOString().split('T')[0] : '';

// 上传头像逻辑
const customEditAvatarUpload = async (options) => {
  const { file } = options;
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await uploadHttp.post('/upload/file', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });

    if (response.code === 200) {
      handleEditAvatarSuccess(response.data);
    } else {
      ElMessage.error('上传失败: ' + response.msg);
    }
  } catch (error) {
    console.error('上传错误:', error);
    ElMessage.error('上传失败');
  }
};

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

const handleEditAvatarSuccess = (res) => {
  editAvatarUrl.value = res;
  editForm.photo = res;
};

// 动态计算表格高度
const calculateTableHeight = () => {
  const windowHeight = window.innerHeight;
  // 为表格留出适当的空间（顶部120px + 底部分页区域80px）
  tableHeight.value = windowHeight - 200;
};

// 组件挂载时加载数据和设置表格高度
onMounted(() => {
  loadEmployees();
  calculateTableHeight();
  window.addEventListener('resize', calculateTableHeight);
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', calculateTableHeight);
});
</script>

<style scoped>
.employee-container {
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.search-card { margin-bottom: 20px; }
.toolbar { margin-bottom: 20px; text-align: right; }
.avatar { width: 100px; height: 100px; border-radius: 50%; object-fit: cover; }
.table-avatar { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; }
.avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 100px; height: 100px; line-height: 100px; text-align: center; border: 1px dashed #d9d9d9; border-radius: 6px; display: inline-block; }
</style>















